package velocity;

import entity.DatebaseEntity;
import utils.StringUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * describe mysql工具类
 * author wencong 2022/3/3
 */
public class MysqlUtils {

    private static String ip = "101.34.173.191";
    private static String prot = "50001";
    private static String database = "hmerpcloudasp";
    private static String username = "wencong";
    private static String password = "wencong863";

    public static int getId(String sql){
        Map<Integer, String> paramMap = new HashMap<>();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try{
            resultSet = getMysqlData(sql, paramMap, connection, preparedStatement);
            while (resultSet.next()) {
                return resultSet.getInt("id");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            mysqlReleaseResources(resultSet, preparedStatement, connection);
        }
        return 0;
    }

    public static TableEntity getTableEntity(String tableName) {
        TableEntity tableEntity = new TableEntity();
        String sql = "select table_name as tableName, table_comment as tableComment from information_schema.tables where table_schema = ? and table_name = ? ";
        Map<Integer, String> paramMap = new HashMap<>();
        paramMap.put(1, database);
        paramMap.put(2, tableName);
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try{
            resultSet = getMysqlData(sql, paramMap, connection, preparedStatement);
            while (resultSet.next()) {
                tableEntity.setTableName(resultSet.getString("tableName"));
                tableEntity.setTableName1(StringUtil.upperStr(resultSet.getString("tableName")));
                tableEntity.setTableName2(StringUtil.lowerStr(resultSet.getString("tableName")));
                tableEntity.setTableComment(resultSet.getString("tableComment"));
                tableEntity.setTableComment1(resultSet.getString("tableComment").replaceAll("表", ""));
                tableEntity.setModular(resultSet.getString("tableName").substring(0, tableEntity.getTableName().contains("_") ? tableEntity.getTableName().indexOf("_") : tableEntity.getTableName().length()));
                tableEntity.setModular1(StringUtil.upperStr(resultSet.getString("tableName").substring(0, tableEntity.getTableName().contains("_") ? tableEntity.getTableName().indexOf("_") : tableEntity.getTableName().length())));
                tableEntity.setRoute(StringUtil.lowerStr(resultSet.getString("tableName").substring(tableEntity.getTableName().indexOf("_")+1)));
                tableEntity.setRoute1(StringUtil.upperStr(resultSet.getString("tableName").substring(tableEntity.getTableName().indexOf("_")+1)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mysqlReleaseResources(resultSet, null, null);
        }
        return tableEntity;
    }
    // 列
    public static List<ColumnEntity> getColumnEntityList(String tableName) {
        List<ColumnEntity> columnEntityList = new ArrayList<>(64);
        String sql = "select column_name as columnName, data_type as dataType, column_comment as columnComment, " +
                "ifnull(character_maximum_length, 0) as characterMaximumLength, is_nullable as isNullable " +
                "from information_schema.columns where table_schema = ? and table_name = ? order by ordinal_position";
        Map<Integer, String> paramMap = new HashMap<>();
        paramMap.put(1, database);
        paramMap.put(2, tableName);
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try{
            resultSet = getMysqlData(sql, paramMap, connection, preparedStatement);
            while (resultSet.next()) {
                ColumnEntity columnEntity = new ColumnEntity();
                columnEntity.setColumnName(resultSet.getString("columnName"));
                columnEntity.setColumnName1(StringUtil.upperStr(resultSet.getString("columnName")));
                columnEntity.setColumnName2(StringUtil.lowerStr(resultSet.getString("columnName")));
                columnEntity.setDataType(resultSet.getString("dataType"));
                columnEntity.setDataType1(typeMap.get(resultSet.getString("dataType")));
                columnEntity.setDataType2(vueTypeMap.get(resultSet.getString("dataType")));
                columnEntity.setColumnComment(resultSet.getString("columnComment"));
                if (resultSet.getString("columnComment").contains(" ")){
                    columnEntity.setColumnComment1(resultSet.getString("columnComment").substring(0, resultSet.getString("columnComment").indexOf(" ")));
                } else {
                    columnEntity.setColumnComment1(resultSet.getString("columnComment"));
                }
                columnEntityList.add(columnEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mysqlReleaseResources(resultSet, preparedStatement, connection);
        }
        return columnEntityList;
    }

    /**
     * 执行mysql语句
     * @param sql 定义sql语句 ?表示占位符
     * @param paramMap 设置参数，第一个参数为sql语句中参数的序号（从1开始），第二个参数为设置的参数值
     */
    public static ResultSet getMysqlData(String sql, Map<Integer, String> paramMap,
                                         Connection connection, PreparedStatement preparedStatement) throws Exception {
        // mysql数据库链接地址
        StringBuilder url = new StringBuilder();
        url.append("jdbc:mysql://").append(ip).append(":").append(prot)
                .append("/").append(database).append("?useSSL=false&serverTimezone=UTC");
        // 加载数据库驱动 mysql8
        Class.forName("com.mysql.cj.jdbc.Driver");
        // 通过驱动管理类获取数据库连接
        connection = DriverManager.getConnection(url.toString(), username, password);
        // 获取预处理statement
        preparedStatement = connection.prepareStatement(sql);
        for (int i = 1; i <= paramMap.size(); i++) {
            preparedStatement.setString(i, paramMap.get(i));
        }
        // 向数据库发出sql执行查询，查询出结果集
        return preparedStatement.executeQuery();
    }

    // 释放资源
    public static void mysqlReleaseResources(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection){
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static Map<String, String> typeMap = new HashMap<>(){{
        put("tinyint", "int?");
        put("smallint", "int?");
        put("mediumint", "int?");
        put("int", "int?");
        put("integer", "int?");
        put("bigint", "long?");
        put("float", "float?");
        put("double", "double?");
        put("decimal", "double?");
        put("date", "DateTime");
        put("time", "DateTime");
        put("year", "DateTime");
        put("datetime", "DateTime");
        put("timestamp", "DateTime");
        put("char", "string");
        put("varchar", "string");
        put("tinyblob", "string");
        put("tinytext", "string");
        put("blob", "string");
        put("text", "string");
        put("mediumblob", "string");
        put("mediumtext", "string");
        put("longblob", "string");
        put("longtext", "string");
    }};

    public static Map<String, String> vueTypeMap = new HashMap<>(){{
        put("tinyint", "number");
        put("smallint", "number");
        put("mediumint", "number");
        put("int", "number");
        put("integer", "number");
        put("bigint", "number");
        put("float", "number");
        put("double", "number");
        put("decimal", "number");
        put("date", "number");
        put("time", "number");
        put("year", "number");
        put("datetime", "number");
        put("timestamp", "number");
        put("char", "string");
        put("varchar", "string");
        put("tinyblob", "string");
        put("tinytext", "string");
        put("blob", "string");
        put("text", "string");
        put("mediumblob", "string");
        put("mediumtext", "string");
        put("longblob", "string");
        put("longtext", "string");
    }};
}
